package com.jzo2o.orders.dispatch.strategys;

import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.orders.dispatch.model.dto.ServeProviderDTO;
import com.jzo2o.orders.dispatch.rules.IDispatchRule;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 规则: 距离近者优先
 */
public class DistanceRule extends AbstractProcessRule {
//    private IProcessRule next;

    public DistanceRule(IProcessRule next) {
//        this.next = next;
        super(next);
    }

//    @Override
//    public List<ServeProviderDTO> filter(List<ServeProviderDTO> serveProviderDTOS) {
//        List<ServeProviderDTO> result = this.doFilter(serveProviderDTOS);
//
//        //如果没有下一级规则,直接返回结果
//        if (next == null) {
//            return result;
//        }
//        if (CollUtils.size(result) <= 1) {
//            // 选出唯一的服务者了,直接返回
//            return result;
//        }
//
//        // 选不出唯一的,就调下一个规则进行筛选
//        return next.filter(result);
//    }

    //挑选距离最近的服务者列表返回
    public List<ServeProviderDTO> doFilter(List<ServeProviderDTO> serveProviderDTOS) {
        System.out.println("按距离排序");
        if (CollUtils.size(serveProviderDTOS) < 2) {
            return serveProviderDTOS;
        }
        // 2.按照比较器进行排序，排在最前方优先级最高
        serveProviderDTOS = serveProviderDTOS.stream()
                .sorted(Comparator.comparing(ServeProviderDTO::getAcceptanceDistance))
                .collect(Collectors.toList());

        // 3.遍历优先级最高一个数据
        ServeProviderDTO first = CollUtils.getFirst(serveProviderDTOS);

        //获取跟第一个相同级别的
        return serveProviderDTOS.stream()
                .filter(origin -> origin.getAcceptanceDistance().compareTo(first.getAcceptanceDistance()) == 0)
                .collect(Collectors.toList());
    }
}